package com.ssyt.yt1.day27;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * <pre>
 * Callable（了解）
 * 面试题1：有哪些方式实现多线程？
 *   1）extends Thread
 *   2）implements Runnable
 *   3）implements Callable
 * 面试题2：implements Runnable和implements Callable的区别？
 *   1）implements Callable可以有返回值
 *   2）implements Callable可以抛出异常
 * </pre>
 * 
 * @author Hsu.
 * @since 2015年12月31日
 */
public class CallableDemo {

	public static void main(String[] args) throws InterruptedException,
			ExecutionException {
		Callable<String> callable = new TicketsByCallable();
		FutureTask<String> futureTask = new FutureTask<String>(callable);
		new Thread(futureTask).start();
		// get()方法一旦被调用，就会阻塞程序的向下执行
		String result = futureTask.get();
		System.out.println(result);
	}
}

class TicketsByCallable implements Callable<String> {

	private int ticktes = 100;

	@Override
	public String call() throws Exception {
		for (int i = 0; i < 100; i++) {
			if (ticktes > 0) {
				System.out.println(Thread.currentThread().getName() + ", 剩余票数："
						+ --ticktes);
			}
		}
		return "票已售完！";
	}

}
